<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    :rules="rules"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input
        v-model="userInfo.password"
        type="password"
        style="width:300px"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="hSubmit">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
// 根据id获取用户信息api, 修改员工信息api
import { getUserDetailById, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      // 表单数据
      userInfo: {
        username: '',
        password: ''
      },
      // 表单验证对象
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.loadUserDetailById()
  },
  methods: {
    // 跟据id获取员工详情函数
    async loadUserDetailById() {
      try {
        // (1) 获取数据
        const res = await getUserDetailById(this.$route.query.id)
        // (2) 保存数据
        this.userInfo = res.data
      } catch (err) {
        // (3) 错误提示
        console.log(err)
      }
    },

    // 修改员工信息函数
    async doSubmit() {
      try {
        // (1) 获取数据
        await saveUserDetailById(this.userInfo)
        // (2) 成功提示
        this.$message.success('恭喜，修改成功！')
        // (3) 跳转employees 页
        this.$router.push('/employees')
      } catch (err) {
        // (4) 错误提示
        this.$message.error('修改失败！')
        console.log(err)
      }
    },

    // 点了确定跟新
    hSubmit() {
      // 兜底验证
      this.$refs.userForm.validate(vali => {
        if (!vali) return
        this.doSubmit()
      })
    }
  }
}
</script>
